//
//  LogViewController.m
//  zuixin
//
//  Created by QJY on 14-8-22.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "LogViewController.h"
#import "MBProgressHUD.h"
#import "Header.h"
#import "NetAccess.h"
#import "DingSh.h"
#import "AFNetworking.h"
#import "AFHTTPRequestOperation.h"
#import "CallViewController.h"
#import "KefuViewController.h"
#import "HgViewController.h"
#import "Base64Encry.h"
#import "ZifViewController.h"

@interface LogViewController ()<UITextFieldDelegate,NSURLConnectionDataDelegate>

@end

@implementation LogViewController
{
    UITextField *_field;
    UITextField *_field1;
    UITextField *_field2;
    UITextField *_field3;
    UITextField *_field4;
    UIButton *_btn;
    UIButton *_btn1;
    UIButton *_btn2;
    BOOL c;
    NSMutableData *_data;
    UIAlertView *_alertView;
    NSString *_string;
    UIImageView *_imageView;
    MBProgressHUD *pro;
    NSUserDefaults *users;
    UIButton*btn2;
    UIButton*btn1;
    UITextField*filed1;
    UITextField*filed2;
    UIView* _view1;
    UIView* _view;
    UIImageView *imgView;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.view removeFromSuperview];
    [_field1 resignFirstResponder];
    [_field2 resignFirstResponder];
    _field1.text =nil;
    _field2.text=nil;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (DeviceHeight==568) {
        imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"beijing.jpg"]];
        imgView.frame = self.view.bounds;
        imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self.view insertSubview:imgView atIndex:0];
    }
    else
    {
        imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"beijing960.jpg"]];
        imgView.frame = self.view.bounds;
        imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self.view insertSubview:imgView atIndex:0];
    }
    
    [self addImgView];
    [self textfield];
    [self addBtn];
    
    
    
    
    
    
}
-(void)addImgView
{
    _imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"114.png"]];
    _imageView.frame =CGRectMake(95, 40 ,120, 120);
    UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(110, 130, 90, 40)];
    label.text=@"乐乎";
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:22];
    label.textColor=[UIColor redColor];
    [self.view addSubview:_imageView];
    //    [self.view addSubview:label];
}
-(void)addBtn
{
    _btn =[UIButton buttonWithType:UIButtonTypeCustom];
    _btn .frame =CGRectMake(20, _field2.frame.origin.y+55+35, 280, 40);
    //[_btn setBackgroundImage:[UIImage imageNamed:@"denglu.png"] forState:UIControlStateNormal];
    _btn.backgroundColor=[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1];
    [_btn setTitle:@"注册" forState:UIControlStateNormal];
    _btn.titleLabel.textColor=[UIColor whiteColor];
    _btn.titleLabel.textAlignment=1;
    _btn.titleLabel.font=[UIFont systemFontOfSize:18];
    [_btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    _btn.tag=90;
    [self.view addSubview:_btn];
    
    _btn1=[UIButton buttonWithType:UIButtonTypeCustom];
    _btn1.frame=CGRectMake(20, _btn.frame.origin.y+_btn.frame.size.height+10, 100, 40) ;
    
    [_btn1 setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [_btn1 setTitleColor:[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1]forState:UIControlStateNormal];
    _btn1.titleLabel.font=[UIFont systemFontOfSize:14];
    [_btn1 setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [_btn1 addTarget:self action:@selector(btnClick1) forControlEvents:UIControlEventTouchUpInside];
    [_btn1 bringSubviewToFront:self.view];
    [self.view addSubview:_btn1];
    _btn2=[UIButton buttonWithType:UIButtonTypeCustom];
    [_btn2 setTitleColor:[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1] forState:UIControlStateNormal];
    _btn2.frame=CGRectMake(200, _btn.frame.origin.y+_btn.frame.size.height+10, 100, 40) ;
    [_btn2 setTitle:@"登录" forState:UIControlStateNormal];
    //[_btn2 setTitleColor:[UIColor colorWithRed:1 green:0 blue: 0 alpha:1] forState:UIControlStateNormal];
    [_btn2 setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    _btn2.titleLabel.font=[UIFont systemFontOfSize:14];
    [self.view addSubview:_btn2];
    
    [_btn2 addTarget:self action:@selector(btnClick2) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}
-(void)btnClick1
{
    // [self presentViewController:[KefuViewController alloc] animated:YES completion:nil];

    
        ZifViewController *micro=[[ZifViewController alloc]init];
        micro.phoneString=_field.text;
        [self presentViewController:micro animated:YES completion:nil];
}
  
-(void)btnClick2
{
   
    [self presentViewController:[[HgViewController alloc]init] animated:YES completion:nil];
    }
-(void)quxiao
{
    NSLog(@"大家好");
    _view1.hidden=YES;
    _view.hidden=YES;
}
-(void)sleep
{
    UIButton*button=(UIButton*)[self.view viewWithTag:90];
    button.userInteractionEnabled=YES;
}

-(void)btnClick:(UIButton*)sender
{

    pro=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    sender.userInteractionEnabled=NO;
//    [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(sleep) userInfo:nil repeats:NO];
    [self performSelector:@selector(sleep) withObject:nil afterDelay:2.0f];
    
    NetAccess *net =[NetAccess sharedNetAccess];
    if(![net haveNet])
    {
        [pro removeFromSuperview];
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
        
        
    }
    else
    {
        
        NSLog(@"111111%@%@",_field2.text,_field1.text);
        if (IOS5) {
            if (!(_field1.text||_field2.text))
            {
                [pro removeFromSuperview];
                _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码或密码为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [_alertView show];
            }
            else{
                [self getShuJu];
            }
        }
        else
        {
            
            if ([_field2.text isEqualToString:@""]||[_field1.text isEqualToString:@""])
            {
                [pro removeFromSuperview];
                _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码或密码为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                
                [_alertView show];
                
            }
            else
            {
                [self getShuJu];
            }
        }}
}
-(void)getShuJu
{
    
    
    
   
//    NSString *str=[NSString stringWithFormat:@"http://oemapi2.leehuu.cn/api/vos/Register2?userName=%@&Password=%@&Os=2&Parent=62634",_field1.text,_field2.text];
//    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//
//    NSMutableURLRequest*request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];
//    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *html = operation.responseString;//@"{\"retCode\":-1,\"exception\":\"密码错误！\"}";
//        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
//        if (data==nil) {
//            [pro removeFromSuperview];
//            UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"服务暂时不可用，请稍后尝试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
//        }
//        else
//        {
//        id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
    NSString*urlStr=@"http://oemapi2.leehuu.cn/YXBp/dm9zb2Vt/UmVnaXN0ZXIPQ";
    NSString * parameterStr=[NSString stringWithFormat:@"dXNlck5hbWUPQ=%@&password=%@&os=2&parent=2645421&proxyId=2645421",[Base64Encry switchBase64String:_field1.text],_field2.text];
    NSLog(@"登录%@",[NSString stringWithFormat:@"%@  %@",urlStr,parameterStr]);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        id dict=[Base64Encry switchUrlString:urlStr switchParameterString:parameterStr];
        if ([dict count]) {
            dispatch_async(dispatch_get_main_queue(), ^{  NSLog(@"获取到的注册数据为asd：%@",dict);
                self.excString=[dict objectForKey:@"exception"];
                self.retString=[dict objectForKey:@"retCode"];
                // NSString*userId=[dict objectForKey:@"userId"];
                NSLog(@"%@",self.excString);
                NSLog(@"%@",self.retString);
                NSString *message = @"注册成功,请您体验";
                // 提示框
                //self.retString=@"0";
                if ([self isBlankString:self.retString]) {
                    [pro removeFromSuperview];
                    UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"网络信号不好，请稍后再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alert show];
                }
                else
                {
                    if ([self.retString intValue])
                    {
                        [pro removeFromSuperview];
                        message=self.excString;
                        _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        
                        [_alertView show];
                        return;
                    }
                    else
                        //信息正确
                    {
                        [pro removeFromSuperview];
                        _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        
                        [_alertView show];
                        
                        [_field1 resignFirstResponder];
                        [_field2 resignFirstResponder];
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"textFieldgg" object:users];
                        //本地存储
                        
                        //
                        
                        NSMutableArray *_usert =[NSMutableArray array];
                        [_usert removeAllObjects];
                        users =[NSUserDefaults standardUserDefaults];
                        NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
                        [dict setObject:_field1.text forKey:@"username"];
                        [dict setObject:_field2.text forKey:@"userword"];
                        // [dict setObject:userId forKey:@"userID"];
                        [_usert addObject:dict];
                        [users setObject:_usert forKey:@"newusers1"];
                        [users synchronize];
                        
                        return;
                    }}
                
            });
        }
        
    });
   
      }
//    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        UIAlertView*alertV=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"请求超时，请检查网络设置或稍后重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil,nil];
//
//        [alertV show];
//    }];
//
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//    [queue addOperation:operation];
//
//}
- (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    
    return NO;
}



#pragma mark--网络代理方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _data =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}
//-(void)connectionDidFinishLoading:(NSURLConnection *)connection
//{
//    NSString *hk =[[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding];
//    NSArray *sdg =[hk componentsSeparatedByString:@":"];
//    NSString *hui =[sdg objectAtIndex:1];
//    NSArray *bhu =[hui componentsSeparatedByString:@","];
//    //_string =[bhu objectAtIndex:0];
//    if([_string hasPrefix:@"0"])
//    {[pro removeFromSuperview];
//        NSMutableArray *_usert =[NSMutableArray array];
//        [_usert removeAllObjects];
//        users =[NSUserDefaults standardUserDefaults];
//        NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
//        [dict setObject:_field.text forKey:@"username"];
//        [dict setObject:_field1.text forKey:@"userword"];
//        [_usert addObject:dict];
//        [users setObject:_usert forKey:@"newusers1"];
//        [users synchronize];
//
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"textFieldgg" object:users];
//        return;
//    }
//    if([_string hasPrefix:@"-1001"])
//    {
//        [pro removeFromSuperview];
//        UIAlertView *alertV=[[UIAlertView alloc]initWithTitle:@"提示" message:@"用户不存在" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertV show];
//        return;
//    }
//    if([_string hasPrefix:@"-101"])
//    {
//        [pro removeFromSuperview];
//        UIAlertView *alertV=[[UIAlertView alloc]initWithTitle:@"提示" message:@"密码错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertV show];
//        return;
//    }
//    else if([_string hasPrefix:@"-1"])
//    {
//        [pro removeFromSuperview];
//        UIAlertView *alertV=[[UIAlertView alloc]initWithTitle:@"提示" message:@"服务器异常 " delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertV show];
//        return;
//    }
//}
//-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
//{[pro removeFromSuperview];
//    NSString *message =@"亲！网络不给力啊，稍后再试吧..!";
//    _alertView.message = message;
//    [_alertView show];
//}
-(void)textfield
{
    _field1 =[[UITextField alloc]initWithFrame:CGRectMake(20,170+40, 320-40,35)];
    _field1.backgroundColor =[UIColor whiteColor];
    _field1.borderStyle = UITextBorderStyleLine;
    _field1 .delegate =self;
    _field1.placeholder = @"手机号:";
    // _field.alpha=0;
    _field1.background=[UIImage imageNamed:@"beijingkuang1.png"];
    _field1.textAlignment=NSTextAlignmentCenter;
    UIImageView *view1=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"shoujihao.png"]];
    view1.frame=CGRectMake(5, 0, 29, 29);
    [_field1 addSubview:view1];
    _field1.keyboardType=UIKeyboardTypeNumberPad;
    //UILabel*label=[UILabel alloc]initWithFrame:CGRectMake(25, 0, 30, 35);
    
    [self.view addSubview:_field1];
    
    _field2 =[[UITextField alloc]initWithFrame:CGRectMake(20,_field1.frame.origin.y+35, 320-40,35)];
    [_field2 setBackground:[UIImage imageNamed:@"beijingkuang2.png"]];
    _field2.borderStyle =UITextBorderStyleLine;
    _field2 .delegate =self;
    _field2.placeholder = @"请输入自定义密码:";
    _field2.secureTextEntry=YES;
    _field2.keyboardType=UIKeyboardTypeNumberPad;
    _field2.textAlignment=1;
    UIImageView *view2=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"password.png"]];
    view2.frame=CGRectMake(5, 0, 29, 29);
    [_field2 addSubview:view2];
    [self.view addSubview:_field2];
  
    UIView *view =[[UIView alloc]initWithFrame:CGRectMake(20,_field2.frame.origin.y+35, 320-40,35)];
   
    //[self.view addSubview:view ];
    UIImageView*imgV=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"beijingkuang2.png"]];
    imgV.frame=CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
    imgV.userInteractionEnabled=YES;
    //[view addSubview:imgV];
    
    _field3=[[UITextField alloc]initWithFrame:CGRectMake(20, 0, 100, view.frame.size.height) ];
    _field3.placeholder=@"输入验证码:";
    _field3.delegate=self;
    _field3.textAlignment=1;
    _field3.keyboardType=UIKeyboardTypeNumberPad;
   // [imgV addSubview:_field3];
    
    UIButton*btn=[UIButton buttonWithType:UIButtonTypeSystem];
    //btn.backgroundColor=[UIColor redColor];
    btn.frame=CGRectMake(150, 0, 120, view.frame.size.height);
    [btn  setTitle:@"获取语音验证码" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor=[UIColor clearColor];
   // [imgV addSubview:btn];
    
}
 -(void)getCode

{  NetAccess *net =[NetAccess sharedNetAccess];
    if(![net haveNet])
    {
       
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
        
        
    }
    else
    {

    if (IOS5) {
        if (!(_field1.text)) {
            _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [_alertView show];
            
        }
        else
        {
            [self getShuJu11];
        }
        
    }
    else
    {
        if ([_field1.text isEqualToString:@""]) {
            _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [_alertView show];
            
        }
        else
        {
            [self getShuJu11];
        }
    }
    }}
 -(void)getShuJu11
{
    NSString *str=[NSString stringWithFormat:@"http://oemapi2.leehuu.cn/api/agent/validatecode?phone=%@&s=1&type=2",_field1.text];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = operation.responseString;//@"{\"retCode\":-1,\"exception\":\"密码错误！\"}";
        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
        id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
        NSLog(@"获取到的数据为asd：%@",dict);
        NSString *reason=[dict objectForKey:@"message"];
        NSString * code=[dict objectForKey:@"code"];
        
        if ([code intValue])
        {
            _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:reason delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [_alertView show];
       
        }
        else
        {
            
            _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"获取成功，请等待" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [_alertView show];
        }
        return;
    
     }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"发生错误！%@",error);
     }];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
    
}




     


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_field resignFirstResponder];
    [_field1 resignFirstResponder];
    [_field2 resignFirstResponder];
    [_field3 resignFirstResponder];
    [_field4 resignFirstResponder];
    [filed1 resignFirstResponder];
    [filed2 resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}
//键盘上下移动
-(void)textFieldDidBeginEditing:(UITextField *)textField{   //开始编辑时，整体上移
    //    if (textField.tag==0) {
    //        [self moveView:-20];
    //    }
    //    if (textField.tag==1)
    //    {
    [self moveView:-80];
    //    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{     //结束编辑时，整体下移
    //    if (textField.tag==0) {
    //        [self moveView:20];
    //    }
    //    if (textField.tag==1)
    //    {
    [self moveView:80];
    //    }
}
-(void)moveView:(float)move{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    frame.origin.y+=move;//view的X轴上移
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];//设置调整界面的动画效果
    
    
}
-(void)changeKeyBoards
{
    _field.keyboardType=UIKeyboardTypeNumberPad;
    _field1.keyboardType=UIKeyboardTypeNumberPad;
    _field3.keyboardType=UIKeyboardTypeNumberPad;
    filed1.keyboardType=UIKeyboardTypeNumberPad;
    filed2.keyboardType=UIKeyboardTypeNumberPad;
    _field.returnKeyType=UIReturnKeyDone;
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
